#include "deletehistorydialog.h"

DeleteHistoryDialog::DeleteHistoryDialog(QWidget *parent):QDialog(parent=nullptr)
{
    setUi();
    loadDeleteHistory();
}

void DeleteHistoryDialog::setUi()
{
    setWindowTitle(tr("管理员: 删除历史记录"));
    setFixedSize(480,360);
    setStyleSheet("background-color: #DBEAFE;"); // 浅蓝色 (RGB: 219, 234, 254)

    //主布局
    QVBoxLayout *mainlayout=new QVBoxLayout(this);
    QLabel *titleLabel=new QLabel("已删除列表");
    titleLabel->setStyleSheet("background-color: #409EFF;");
    mainlayout->addWidget(titleLabel);

    listwidget=new QListWidget();
    // 设置浅灰色背景和深灰色文本的列表样式
    QFile file("qrc:/qss/style1.qss");
    if(file.open(QFile::Text|QFile::ReadOnly))
    {
        setStyleSheet(file.readAll());
        file.close();
    }
    mainlayout->addWidget(listwidget);

    listwidget->setContextMenuPolicy(Qt::CustomContextMenu); //启用右键菜单
    connect(listwidget,&QListWidget::customContextMenuRequested,this,&DeleteHistoryDialog::showDeleteMenu);


}
void DeleteHistoryDialog::loadDeleteHistory()
{
    QSqlQuery query("SELECT original_id,question,deleted_data FROM deleted_history ORDER BY deleted_data DESC ");
    if(!query.exec())
    {
        QMessageBox::critical(this,"error","无法加载删除历史记录");
        return;
    }
    while(query.next())
    {
        int id=query.value(0).toInt();
        QString question=query.value(1).toString();
        QDateTime  time=query.value(2).toDateTime();
        QString displayText=QString("[id:%1] %2  删除时间 %3").arg(id).arg(question).arg(time.toString("yyyy-MM-dd HH:mm:ss"));
        QListWidgetItem *item=new QListWidgetItem(displayText);
        item->setData(Qt::UserRole,id);
        item->setToolTip(QString("QUESTION:%1\n").arg(question));

        listwidget->addItem(item);

    }
}

void DeleteHistoryDialog::refreshHistory()        //删除后刷新表
{
    listwidget->clear();
    loadDeleteHistory();
}
void DeleteHistoryDialog::showDeleteMenu(const QPoint &pos)                      //展示菜单
{
    QMenu menu(this);
    QAction *deleteAction=menu.addAction("永久删除");
    QAction *tipAction=menu.addAction("提示");
    connect(deleteAction,&QAction::triggered,this,&DeleteHistoryDialog::deleteSelectRecords);

    connect(tipAction,&QAction::triggered,this,[this]{
        QMessageBox::information(this,"提醒","将会永久删除不可恢复，并记录日志");
    });
    menu.exec(listwidget->mapToGlobal(pos));

}
void DeleteHistoryDialog::deleteSelectRecords()        //删除选中的记录
{
    QList<QListWidgetItem *> selectedItems = listwidget->selectedItems();

    // 检查是否有选中项
    if (selectedItems.isEmpty()) {
        QMessageBox::information(this, "提示", "请先选择要删除的记录");
        return;
    }

    // 确认对话框
    QMessageBox::StandardButton reply;
    reply = QMessageBox::warning(
        this,
        "确认删除",
        QString("确定要删除选中的 %1 条记录吗？此操作不可恢复。").arg(selectedItems.size()),
        QMessageBox::Yes | QMessageBox::No
        );

    if (reply != QMessageBox::Yes)
    {
        return; // 用户取消删除
    }
    QSqlDatabase db=QSqlDatabase::database();
    if(!db.isOpen())
    {
        QMessageBox::information(this,"错误","数据库连接失败,请重新检查");
        return;
    }
    QFile logFile("operation.log");
    if(!logFile.open(QIODevice::Append|QIODevice::Text))
    {
        QMessageBox::information(this,"错误","数据库连接失败,请重新检查");
    }
    db.transaction();   //开启事务

    bool success=true;
    for(auto *item:selectedItems)
    {
        int id=item->data(Qt::UserRole).toInt();
        QString question=item->toolTip().split("\n")[0].mid(9);

        //删除操作
        QSqlQuery query;
        query.prepare("DELETE FROM deleted_history WHERE original_id=?");
        query.addBindValue(id);

        if(!query.exec())
        {
            success=false;
            QMessageBox::information(this,"错误",QString("删除失败：%1 ，%2").arg(query.lastError().text()).arg(query.lastQuery()));
            break;
        }
        if(logFile.isOpen())
        {
            QTextStream stream(&logFile);
            stream<<QDateTime::currentDateTime().toString("[yyyy-MM-dd HH:mm:ss]")
            <<" [id]:"<<id
            <<" question:"<<question<<"\n";

        }
        if(success)
        {
            db.commit();
            refreshHistory();
            QMessageBox::information(this,"成功","系统提示:已永久删除选定记录");

        }
        else
        {
            db.rollback();
            QMessageBox::information(this,"成功","系统提示:操作已回滚");
        }
    }
}










//
